package com.zhkc.wisdom.common.web.desensitization;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.zhkc.wisdom.common.web.desensitization.annotation.Desensitized;

import java.io.IOException;
import java.util.Objects;

public class SensitiveSerialize extends JsonSerializer<String> implements ContextualSerializer {

    /**
     * 脱敏类型
     */
    private SensitiveTypeEnum type;


    private String getString(String value, SensitiveTypeEnum type) {
        switch (type) {
            case ID_CARD:
                value = DesensitizationUtils.idCardNum(value);
                break;
            case MOBILE_PHONE:
                value = DesensitizationUtils.mobilePhone(value);
                break;
            case ADDRESS:
                value = DesensitizationUtils.address(value, 8);
                break;
            case EMAIL:
                value = DesensitizationUtils.email(value);
                break;
            case BANK_CARD:
                value = DesensitizationUtils.bankCard(value);
                break;
            default:
        }
        return value;
    }


    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString( getString(s,this.type));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        // 为空直接跳过
        if (beanProperty != null) {
            // 非 String 类直接跳过
            if (Objects.equals(beanProperty.getType().getRawClass(), String.class)) {
                Desensitized sensitiveWrapped = beanProperty.getAnnotation(Desensitized.class);
                if (sensitiveWrapped == null) {
                    sensitiveWrapped = beanProperty.getContextAnnotation(Desensitized.class);
                }
                if (sensitiveWrapped != null) {
                    // 如果能得到注解，就将注解的 value 传入 SensitiveSerialize
                    return new SensitiveSerialize(sensitiveWrapped.type());
                }
            }
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        return serializerProvider.findNullValueSerializer(beanProperty);
    }

    public SensitiveSerialize() {}

    public SensitiveSerialize(final SensitiveTypeEnum type) {
        this.type = type;
    }
}
